<template>
    <el-form label-width="100px" :inline="false" size="default">
        <el-form-item label="SPU名称" size="default">
            <el-input v-model="now_spu_form.spuName" placeholder="请输入SPU名称" />
        </el-form-item>
        <el-form-item label="SPU品牌" size="default">
            <el-select v-model="now_spu_form.tmId" placeholder="请选择SPU品牌">
                <el-option v-for="item in all_trade_mark" :key="item.id" :label="item.tmName"
                    :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="SPU描述" size="default">
            <el-input v-model="now_spu_form.description" placeholder="请输入SPU描述" type="textarea" :rows=4 />
        </el-form-item>
        <el-form-item label="SPU图片" size="default">
            <el-upload v-model:file-list="spu_image_list" action="/api/admin/product/fileUpload"
                list-type="picture-card" :on-preview="handlePictureCardPreview" :before-upload="beforeAvatarUpload">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性" size="default" class="spu-attr-form-item">
            <el-select v-model="selected_spu_sale_attr_nameandid" clearable filterable class="spu-attr-select"
                :placeholder="unhas_sale_attr.length ? '请选择销售属性' : '没有可选销售属性'">
                <el-option v-for="item in unhas_sale_attr" :key="item.id" :label="item.name"
                    :value="`${item.name}-${item.id}`"></el-option>
            </el-select>
            <el-button type="primary" @click="add_spu_sale_attr"
                :disabled="!selected_spu_sale_attr_nameandid">添加销售属性</el-button>
            <el-table border :data="spu_has_sale_attr">
                <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
                <el-table-column label="销售属性名称" width="180" align="center" prop="saleAttrName"></el-table-column>
                <el-table-column label="销售属性值" align="center">
                    <template #default="scope">
                        <el-tag v-for="(item, index) in scope.row.spuSaleAttrValueList" :key="index" closable
                            @close="scope.row.spuSaleAttrValueList.splice(index, 1)">
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                            @keyup.enter="handleInputConfirm" @blur="handleInputConfirm(scope.row)" />
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">
                            + New Tag
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="spu_has_sale_attr.splice(scope.$index, 1)"
                            icon="Delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submit_spu_data">提交</el-button>
            <el-button type="primary" @click="handle_cancel">取消</el-button>
        </el-form-item>


    </el-form>


</template>
<script setup lang="ts">
import type { SpuData, SpuHasSaleAttr, BaseSaleAttr, SpuHasSaleAttrValue } from '@/api/product/spu/type';
import { computed, nextTick, onMounted, ref } from 'vue';
import type { Trademark } from '@/api/product/trademark/type';
import { reqAddorEditSpu, reqAllTradeMark, reqBaseSaleAttr, reqSpuHasSaleAttr, reqSpuImageList } from '@/api/product/spu';
import { ElMessage, type UploadProps } from 'element-plus';
import type { InputInstance } from 'element-plus/lib/components/index.js';
let scene = defineModel<number>('scene')
let prop = defineProps<{
    now_edit_spu: SpuData,
    flush_spu_list: () => void,
    category3_id: number
}>()
// 图片预览
let dialogVisible = ref(false)
let dialogImageUrl = ref('')
// 所有品牌
let all_trade_mark = ref<Trademark[]>([])
// 当前SPU图片列表
let spu_image_list = ref<any[]>([])
// 当前SPU销售属性列表
let spu_has_sale_attr = ref<SpuHasSaleAttr[]>([])
// 所有销售属性
let all_sale_attr = ref<BaseSaleAttr[]>([])
// 当前SPU表单
let now_spu_form = ref<SpuData>({
    spuName: '',
    description: '',
    category3Id: 1,
    tmId: 1,
    spuSaleAttrList: [],
    spuImageList: []
})
// 选中的销售属性名称和id
let selected_spu_sale_attr_nameandid = ref<string>('')

// 新添加的销售属性
onMounted(() => {
    if (prop.now_edit_spu.id) {
        reqAllTradeMark().then(res => {
            all_trade_mark.value = res.data
        })
        reqBaseSaleAttr().then(res => {
            all_sale_attr.value = res.data
        })
        if (prop.now_edit_spu.id) {
            reqSpuImageList(prop.now_edit_spu.id).then(res => {
                spu_image_list.value = res.data.map(item => {
                    return {
                        name: item.imgName,
                        url: item.imgUrl
                    }
                })
            })
            reqSpuHasSaleAttr(prop.now_edit_spu.id).then(res => {
                spu_has_sale_attr.value = res.data
            })
            now_spu_form.value = prop.now_edit_spu
        }
    }
    else {
        reqAllTradeMark().then(res => {
            all_trade_mark.value = res.data
        })
        reqBaseSaleAttr().then(res => {
            all_sale_attr.value = res.data
        })
        now_spu_form.value.category3Id = prop.category3_id
    }
})
// 图片预览
const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}
// 上传前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('Avatar picture must be JPG or PNG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
//未添加的销售属性
let unhas_sale_attr = computed(() => {
    return all_sale_attr.value.filter(item => {
        return spu_has_sale_attr.value.every(item1 => {
            return item1.saleAttrName !== item.name
        })
    })
})
//添加销售属性
const add_spu_sale_attr = () => {
    if (selected_spu_sale_attr_nameandid.value) {
        const [saleAttrName, baseSaleAttrId] = selected_spu_sale_attr_nameandid.value.split('-')
        let new_add_spu_sale_attr = ref<SpuHasSaleAttr>({
            saleAttrName: '',
            spuSaleAttrValueList: [],
            baseSaleAttrId: 0
        })
        new_add_spu_sale_attr.value.saleAttrName = saleAttrName
        new_add_spu_sale_attr.value.baseSaleAttrId = Number(baseSaleAttrId)
        spu_has_sale_attr.value.push(new_add_spu_sale_attr.value)
        selected_spu_sale_attr_nameandid.value = ''
    }
}
// tag新增的处理
const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InputInstance>()
// 显示输入框
const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}
// 确认tag输入
const handleInputConfirm = (row: SpuHasSaleAttr) => {
    if (inputValue.value) {
        const is_repeat = row.spuSaleAttrValueList.some(item => item.saleAttrValueName === inputValue.value)
        if (is_repeat) {
            ElMessage.error('销售属性值不能重复')
            return
        }
        let new_spu_sale_attr_value = ref<SpuHasSaleAttrValue>({
            saleAttrValueName: inputValue.value,
            baseSaleAttrId: row.baseSaleAttrId,
        })
        row.spuSaleAttrValueList.push(new_spu_sale_attr_value.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}
// 提交SPU数据
const submit_spu_data = async () => {
    //处理图片数组
    let now_spu_image_list = spu_image_list.value.map(item => {
        return {
            imgName: item.name,
            imgUrl: item.url
        }
    })
    //处理销售属性数组
    let now_spu_sale_attr_list = spu_has_sale_attr.value
    //处理SPU表单
    now_spu_form.value.spuImageList = now_spu_image_list
    now_spu_form.value.spuSaleAttrList = now_spu_sale_attr_list
    //console.log(now_spu_form.value)
    const response = await reqAddorEditSpu(now_spu_form.value)
    if (response.code == 200) {
        ElMessage.success('提交成功')
        prop.flush_spu_list()
        scene.value = 0
    }
    else {
        ElMessage.error('提交失败')
    }
}
// 取消
const handle_cancel = () => {
    prop.flush_spu_list()
    scene.value = 0
}
</script>
<style scoped lang="less">
.spu-attr-form-item {
    white-space: nowrap;

    .spu-attr-select {
        width: 240px;
        margin-right: 18px;
    }
}
</style>
